package org.magicbox.qjunTPO.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.Entrust;
import org.magicbox.qjunTPO.entity.SysMessage;
import org.magicbox.qjunTPO.service.EntrustService;
import org.magicbox.qjunTPO.service.SysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 欢迎添加科技实践队粉丝群：690849711
 * @since 2021-12-01
 */
@RestController
@RequestMapping("/entrust")
public class EntrustController {
    @Autowired
    EntrustService entrustService;

    @Autowired
    SysMessageService sysMessageService;
    /**
     * 添加一条委托
     * @param entrust 委托
     * @return 发送结果
     */
    @PreAuthorize("hasAnyRole('LV1','LV2','LV3')")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@Validated @RequestBody Entrust entrust){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid = new Integer(authentication.getName());
        entrust.setStuidConsignor(uid);
        entrust.setCreatedate(LocalDateTime.now());
        entrust.setStuidSuccess(null);
        entrust.setEntrustOkey(0);
        entrust.setEntrustId(null);
        boolean save = entrustService.save(entrust);
        if(save)return Result.success(true);
        else return Result.fail("发布委托失败了",false);
    }

    /**
     * 批量获取委托
     * @param entrustClass 委托类型 0全部 1编程 2视频剪辑 3平面设计 4电脑维修
     * @param pageNumber 页码
     * @return  委托数组
     */
    @RequestMapping("/page")
    public Result page(@PathParam("entrustClass")int entrustClass,
                       @PathParam("pageNumber")Integer pageNumber){
        HashMap<String,Integer> eq = new HashMap<>();
        if (entrustClass!=0) eq.put("type",entrustClass);
        Page page = new Page(pageNumber,20);
        IPage pagedata = entrustService.page(page, new QueryWrapper<Entrust>().allEq(eq));
        return Result.success(pagedata);
    }


    /**
     * 接受委托
     */
    @PreAuthorize("hasAnyRole('LV2','LV3')")
    @RequestMapping("/accept/{entrustID}")
    public Result accept(@PathVariable("entrustID")Integer entrustID){
        Entrust byId = entrustService.getById(entrustID);
        //获取当前用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid =new  Integer(authentication.getName());
        //验证是否可以被接受
        if(byId.getStuidConsignor().equals(uid)) return Result.fail("无法接受自己的委托！",false);
        if (!byId.getEntrustOkey().equals(0)) return Result.fail("无法被接受的状态",false);

        //修改委托接收者 和 修改委托状态
        byId.setStuidSuccess(uid);
        byId.setEntrustOkey(1);
        boolean res_update = entrustService.updateById(byId);

        //给用户发系统信息
        boolean res_msg = sysMessageService.addSysMsg(new SysMessage(null, byId.getStuidConsignor(),
                "您的委托已被接受,点击查看", 5, byId.getEntrustId().longValue()));

        //返回接受结果
        if (res_msg&res_update){
            return Result.success(true);
        }else {
            return Result.fail("出错了 ，程序员不想处理了，你再看看有没有成功吧",false);
        }
    }

    /**
     * 取消委托
     * @param entrustID 委托id
     * @return
     */
    @RequestMapping("/giveUp/{entrustID}")
    public Result giveUp(@PathVariable("entrustID") Integer entrustID){
        //获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Integer uid = new Integer(authentication.getName());
        //获取委托
        Entrust byId = entrustService.getById(entrustID);
        //判断委托是否属于当前用户
        if (!uid.equals(byId.getStuidConsignor())) return Result.fail("没有权限",false);
        //判断委托是未被接受状态
        if (!byId.getEntrustOkey().equals(0))return Result.fail("无法取消的状态",false);
        //修改委托状态
        byId.setEntrustOkey(3);
        entrustService.updateById(byId);
        return Result.success(true);

    }
}
